﻿using HalconDotNet;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HalconExtension.Models
{
    public class HCircleObj : HObjBase
    {
        public HTuple Row { get; set; }

        public HTuple Column { get; set; }

        public HTuple Radius { get; set; }


        /// <summary>
        /// 刷新回调
        /// </summary>
        public Action<HCircleObj> RefleshCallBack { get; set; }

        public HCircleObj(HSmartWindowControlWPF windowControlWPF, HImage hImage, HTuple row, HTuple col, HTuple radius)
        {
            HType = "circle";
            WindowControlWPF = windowControlWPF;
            Image = hImage;
            Row = row;
            Column = col;
            Radius = radius;

            DrawingObject = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.CIRCLE, Row, Column, Radius);

            //添加更新事件
            DrawingObject.OnDrag(Reflash);
            DrawingObject.OnResize(Reflash);
        }

        public HCircleObj(HSmartWindowControlWPF windowControlWPF, HImage hImage) : this(windowControlWPF, hImage, 64, 64, 64)
        {
        }

        public HCircleObj()
        {

        }

        public override void Reflash(HDrawingObject drawid, HWindow window, string type)
        {
            Row = drawid.GetDrawingObjectParams("row");
            Column = drawid.GetDrawingObjectParams("column");
            Radius = drawid.GetDrawingObjectParams("radius");

            //将本身回调
            RefleshCallBack(this);
        }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(new
            {
                row = TwoDecimalPlaces(Row),
                column = TwoDecimalPlaces(Column),
                radius = TwoDecimalPlaces(Radius),
            });
        }
        /// <summary>
        /// 截取图片
        /// </summary>
        public override HObject Reduce()
        {
            HObject res = new HObject();
            HOperatorSet.GenCircle(out ROI, Row, Column, Radius);
            HOperatorSet.ReduceDomain(Image, ROI, out res);
            return res;
        }



        public override Task Draw(Action callback)
        {
            //防止出现多个鼠标绘制任务。强制前一个任务放开
            HalconAPI.CancelDraw();
            HTuple row = new HTuple();
            HTuple column = new HTuple();
            HTuple radius = new HTuple();

            //double row1,row2,column1,column2;
            HOperatorSet.DrawCircle(WindowControlWPF.HalconWindow, out row, out column, out radius);
            //WindowControlWPF.HalconWindow.DrawRectangle1(out row1, out column1, out row2, out column2);
            Row = row;
            Column = column;
            Radius = radius;

            //获取接触的ROI区域
            Reduce();

            callback();
            return Task.CompletedTask;
        }
    }
}
